package com.niodata.dp.expression.function.date;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Map;

public class DayListOfMonthFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "day_list_month";
  }


  public AviatorObject call(Map<String, Object> env, AviatorObject month) {
    String monStr = FunctionUtils.getStringValue(month, env);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
    YearMonth yearMonth = YearMonth.parse(monStr, formatter);
    int days = yearMonth.lengthOfMonth();
    String[] array = new String[days];
    for (int i = 1; i <= days; i++) {
      array[i - 1] = String.format("%02d", i);
    }
    return FunctionUtils.wrapReturn(array);
  }


  public AviatorObject call(Map<String, Object> env, AviatorObject month, AviatorObject format) {
    String monStr = FunctionUtils.getStringValue(month, env);
    String fmt = FunctionUtils.getStringValue(format, env);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(fmt);
    YearMonth yearMonth = YearMonth.parse(monStr, formatter);
    int days = yearMonth.lengthOfMonth();
    String[] array = new String[days];
    String formartStr = FunctionUtils.getStringValue(format, env);
    for (int i = 1; i <= days; i++) {
      array[i - 1] = String.format(formartStr, i);
    }
    return FunctionUtils.wrapReturn(array);
  }
}
